/**
 * 
 */
package com.nari.sink.service;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.nari.baseinfo.dao.IFileMappingDao;
import com.nari.basic.model.IUser;
import com.nari.basic.utils.sysmgr.UserRoleUtil;
import com.nari.coreframe.service.GenericServiceImpl;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResponseMsg;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.sink.bo.ISinkerStandardDict;
import com.nari.sink.dao.ISinkerStandardDictDao;
import com.nari.sink.utils.DictSeriousGenerator;
import com.nari.sink.utils.excelupload.SinkerDictParser;
import com.nari.sink.utils.excelupload.parseentity.ExcelSinkerDictEntity;

/**
 * 
 * @author Xiaopeng
 * @date 2014-4-15
 */
public class SinkerStandardDictServiceImpl extends GenericServiceImpl<ISinkerStandardDict, String>
		implements ISinkerStandardDictService {
	private IFileMappingDao iFileMappingDao;
	private String diskFilePath;
	private String sinkDictFolder;
	
	/**
	 * 分页查询散热器型号字典
	 * @param dictSerious
	 * @param sinkType
	 * @param brand
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-15
	 */
	public ResultWithPageCond<ISinkerStandardDict> querySinkerDictPage(String dictSerious, 
			String sinkType, String brand, PageCond pageCond) throws Exception {
		ISinkerStandardDictDao iSinkerStandardDictDao = (ISinkerStandardDictDao) this.getiGenericDao();
		return iSinkerStandardDictDao.querySinkerDictPage(dictSerious, sinkType, brand, pageCond);
	}
	
	/**
	 * 根据散热器特征信息查询对应型号参数的标准散热器列表
	 * 散热器匹配原则：
	 * 优先级一：主要参数匹配，包括型号、中心距
	 * 优先级二：次要匹配参数，包括品牌、散热器尺寸（高、宽、长）、单片功率
	 * 说明：按照优先级从高到低的结果集最少的匹配原则，结果集越少，说明匹配精确度越高；
	 * 相应的数据冗余度可能越高，即同一型号参数的散热器因为参数等误差未正确匹配
	 * @param sinkerDict
	 * @return
	 * 返回结果说明：
	 * 1、结果集为空或结果集个数为0，说明字典库不存在此型号参数的标准散热器，视为正确匹配
	 * 2、结果集个数为1，说明字典库已存在此型号参数的标准散热器，也视为正确匹配
	 * 3、结果集个数大于1，说明字典库存在多个同种类型参数的标准散热器，视为匹配异常
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-18
	 */
	public List<ISinkerStandardDict> queryByCharacteristicInfo(ISinkerStandardDict sinkerDict) throws Exception {
		ISinkerStandardDictDao iSinkerStandardDictDao = (ISinkerStandardDictDao) this.getiGenericDao();
		return iSinkerStandardDictDao.queryByCharacteristicInfo(sinkerDict);
	}
	
	/**
	 * 带附件上传的标准散热器信息保存及修改
	 * @param sinkerDict
	 * @param attachFile
	 * @param fileName
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-18
	 */
	public ResponseMsg saveOrUpdateSinkerDict(ISinkerStandardDict sinkerDict, File attachFile, 
			String fileName) throws Exception {
		//基本散热器信息更新
		if(sinkerDict.getId()!=null && !"".equals(sinkerDict.getId())) {
			sinkerDict.setUpdateTime(new Date());
			this.getiGenericDao().updateEntity(sinkerDict, sinkerDict.getId());
			//删除散热器原附件
			if(sinkerDict.getPictureNo()!=null && !"".equals(sinkerDict.getPictureNo())) {
				this.iFileMappingDao.deleteFileMapByUID(sinkerDict.getPictureNo());
			}
		} else {
			//型号字典编号
			sinkerDict.setDictSerious(DictSeriousGenerator.generateSeriousUID(sinkerDict.getSinkType(), 
					sinkerDict.getBrand(), sinkerDict.getSinkCenDis()));
			//最后更新时间
			sinkerDict.setUpdateTime(new Date());
			//创建者
			IUser operator = UserRoleUtil.getSysLoginUser();
			sinkerDict.setCreator(operator.getUserID());
			this.getiGenericDao().saveEntity(sinkerDict);
		}
		ResponseMsg rmsg = ResponseMsg.getInstance(true, "");
		//散热器照片附件管理
		if(attachFile != null) {
			rmsg = this.iFileMappingDao.saveAttachmentUpload(attachFile, fileName, diskFilePath, sinkDictFolder);
			if(rmsg.isSuccess()) {
				sinkerDict.setPictureNo(rmsg.getMsg());
				this.getiGenericDao().updateEntity(sinkerDict, sinkerDict.getId());
			}
		}
		return rmsg;
	}
	
	/**
	 * 删除标准散热器照片附件
	 * @param sinkerDictUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-18
	 */
	public ResponseMsg deleteSinkerDictAttachFile(String sinkerDictUID) throws Exception {
		ISinkerStandardDict sinkerDict = this.getiGenericDao().queryEntityById(sinkerDictUID);
		//删除文件附件
		this.iFileMappingDao.deleteFileMapByUID(sinkerDict.getPictureNo());
		//更新散热器信息
		sinkerDict.setPictureNo(null);
		this.getiGenericDao().updateEntity(sinkerDict, sinkerDictUID);
		return ResponseMsg.getInstance(true, "");
	}
	
	/**
	 * 通过标准散热器唯一标识删除散热器信息，并删除对应的散热器照片附件
	 * @param sinkerDictUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-18
	 */
	public ResponseMsg deleteSinkerDictByUID(String sinkerDictUID) throws Exception {
		ISinkerStandardDict sinkerDict = this.getiGenericDao().queryEntityById(sinkerDictUID);
		//删除散热器附件
		if(sinkerDict.getPictureNo()!=null && !"".equals(sinkerDict.getPictureNo())) {
			this.iFileMappingDao.deleteFileMapByUID(sinkerDict.getPictureNo());
		}
		//删除散热器信息
		this.getiGenericDao().deleteEntityById(sinkerDictUID);
		return ResponseMsg.getInstance(true, "");
	}
	
	/**
	 * 为标准散热器添加照片附件
	 * @param attachFile
	 * @param fileName
	 * @param sinkerDictUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-19
	 */
	public ResponseMsg saveSinkerDictImageUpload(File attachFile, String fileName, 
			String sinkerDictUID) throws Exception {
		ISinkerStandardDict sinkerDict = this.getiGenericDao().queryEntityById(sinkerDictUID);
		if(sinkerDict != null) {
			//修改散热器附件时，则删除原附件
			if(sinkerDict.getPictureNo()!=null && !"".equals(sinkerDict.getPictureNo())) {
				this.iFileMappingDao.deleteFileMapByUID(sinkerDict.getPictureNo());
			}
			//上传附件存储
			ResponseMsg rmsg = this.iFileMappingDao.saveAttachmentUpload(attachFile, fileName, diskFilePath, sinkDictFolder);
			if(rmsg.isSuccess()) {
				sinkerDict.setPictureNo(rmsg.getMsg()); 
				this.getiGenericDao().updateEntity(sinkerDict, sinkerDictUID);
				return ResponseMsg.getInstance(true, "");
			}
		}
		return ResponseMsg.getInstance(false, "图片上传失败，请检查型号散热器是否不存在！");
	}
	
	/**
	 * 标准散热器型号数据的批量导入
	 * @param excelFile
	 * @param excelFileName
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-17
	 */
	public ResponseMsg saveOrUpdateSinkerDictBatch(File excelFile, String excelFileName) throws Exception {
		ISinkerStandardDictDao iSinkerStandardDictDao = (ISinkerStandardDictDao) this.getiGenericDao();
		//Excel文件解析
		SinkerDictParser excelParser = SinkerDictParser.getInstance();
		ResponseMsg rmsg = excelParser.parseSinkerDictExcel(excelFile, excelFileName);
		if(rmsg.isSuccess()) {
			//审计Excel导入操作者
			IUser operator = UserRoleUtil.getSysLoginUser();
			//审计Excel导入信息
			boolean validAdapter = false;
			StringBuffer validAdapterInfo = new StringBuffer("");
			boolean invalidAdapter = false;
			StringBuffer invalidAdapterInfo = new StringBuffer("");
			//读取Excel解析信息
			List<ExcelSinkerDictEntity> sinkerDictEntityList = excelParser.getExcelParseData();
			for(Iterator<ExcelSinkerDictEntity> it=sinkerDictEntityList.iterator(); it.hasNext();) {
				ExcelSinkerDictEntity sinkerDictEntity = it.next();
				//散热器特征信息匹配
				ISinkerStandardDict adapterSinkerDict = new ISinkerStandardDict();
				BeanUtils.copyProperties(adapterSinkerDict, sinkerDictEntity);
				List<ISinkerStandardDict> adapterList = iSinkerStandardDictDao.queryByCharacteristicInfo(adapterSinkerDict);
				//同型号参数的标准散热器不存在，此导入为新增散热器型号数据
				if(adapterList==null || adapterList.size()==0) {
					//型号字典编号
					adapterSinkerDict.setDictSerious(DictSeriousGenerator.generateSeriousUID(adapterSinkerDict.getSinkType(), 
							adapterSinkerDict.getBrand(), adapterSinkerDict.getSinkCenDis()));
					//最后更新时间
					adapterSinkerDict.setUpdateTime(new Date());
					//创建者
					adapterSinkerDict.setCreator(operator.getUserID());
					this.getiGenericDao().saveEntity(adapterSinkerDict);
				}
				//同型号参数的标准散热器存在一条记录，此导入为更新散热器型号数据
				if(adapterList!=null && adapterList.size()==1) {
					ISinkerStandardDict storeSinkerDict = adapterList.get(0);
					BeanUtils.copyProperties(storeSinkerDict, sinkerDictEntity);
					//最后更新时间
					adapterSinkerDict.setUpdateTime(new Date());
					this.getiGenericDao().updateEntity(storeSinkerDict, storeSinkerDict.getId());
					//有效匹配信息审计
					validAdapter = true;
					validAdapterInfo.append(sinkerDictEntity.getRowCounter());
					validAdapterInfo.append("；");
				}
				/* 同型号参数的标准散热器存在多条记录，即无法实现正确匹配的情况下，单独导入型号数据，
				 * 但此导入可能形成冗余数据，需要提示用户 */
				if(adapterList!=null && adapterList.size()>1) {
					//型号字典编号
					adapterSinkerDict.setDictSerious(DictSeriousGenerator.generateSeriousUID(adapterSinkerDict.getSinkType(), 
							adapterSinkerDict.getBrand(), adapterSinkerDict.getSinkCenDis()));
					//最后更新时间
					adapterSinkerDict.setUpdateTime(new Date());
					//创建者
					adapterSinkerDict.setCreator(operator.getUserID());
					this.getiGenericDao().saveEntity(adapterSinkerDict);
					//无效匹配信息审计
					invalidAdapter = true;
					invalidAdapterInfo.append(sinkerDictEntity.getRowCounter());
					invalidAdapterInfo.append("；");
				}
			}
			//构造Excel导入审计信息
			StringBuffer excelImportInfo = new StringBuffer();
			if(validAdapter) {
				excelImportInfo.append("★以下行记录信息发现匹配数据，型号字典数据被更新：\\n");
				excelImportInfo.append(validAdapterInfo);
			}
			if(invalidAdapter) {
				excelImportInfo.append("★以下行记录信息发现冗余的匹配数据，请检查手动更新：\\n");
				excelImportInfo.append(invalidAdapterInfo);
			}
			if(validAdapter || invalidAdapter) {
				rmsg = ResponseMsg.getInstance(false, excelImportInfo.toString());
			} else {
				rmsg = ResponseMsg.getInstance(true, "");
			}
		}
		return rmsg;
	}
	
	/**
	 * @return the iFileMappingDao
	 */
	public IFileMappingDao getiFileMappingDao() {
		return iFileMappingDao;
	}

	/**
	 * @param iFileMappingDao the iFileMappingDao to set
	 */
	public void setiFileMappingDao(IFileMappingDao iFileMappingDao) {
		this.iFileMappingDao = iFileMappingDao;
	}

	/**
	 * @return the diskFilePath
	 */
	public String getDiskFilePath() {
		return diskFilePath;
	}

	/**
	 * @param diskFilePath the diskFilePath to set
	 */
	public void setDiskFilePath(String diskFilePath) {
		this.diskFilePath = diskFilePath;
	}

	/**
	 * @return the sinkDictFolder
	 */
	public String getSinkDictFolder() {
		return sinkDictFolder;
	}

	/**
	 * @param sinkDictFolder the sinkDictFolder to set
	 */
	public void setSinkDictFolder(String sinkDictFolder) {
		this.sinkDictFolder = sinkDictFolder;
	}
	
}
